package com.flbill.controller;

import com.flbill.common.result.PageResult;
import com.flbill.common.result.Result;
import com.flbill.pojo.dto.ExpenseDTO;
import com.flbill.pojo.dto.TransactionsDTO;
import com.flbill.pojo.dto.TransactionsPageDTO;
import com.flbill.service.TransactionsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/transactions")
@Slf4j
public class TransactionsController {
    private final TransactionsService transactionsService;

    public TransactionsController(TransactionsService transactionsService) {
        this.transactionsService = transactionsService;
    }
    //添加支出
    @PostMapping("expense")
    public Result Expense(@RequestBody ExpenseDTO expenseDTO) {
        log.info("添加支出:{}", expenseDTO);
        transactionsService.addExpense(expenseDTO);
        return Result.success();
    }

    // 添加收入
    @PostMapping("income")
    public Result addIncome(@RequestBody com.flbill.pojo.dto.IncomeDTO incomeDTO) {
        log.info("添加收入:{}", incomeDTO);
        transactionsService.addIncome(incomeDTO);
        return Result.success();
    }

    //分页查询流水
    @GetMapping("list")
    public Result<PageResult> list(TransactionsPageDTO transactionsPageDTO) {
        log.info("分页查询流水:{}", transactionsPageDTO);
        String type = transactionsPageDTO.getType();
        PageResult pageResult;
        if ("expense".equals(type)) {
            pageResult = transactionsService.ExpensePagelist(transactionsPageDTO);
        } else if ("income".equals(type)) {
            pageResult = transactionsService.IncomePagelist(transactionsPageDTO);
        } else {
            // type 为空或不合法，返回错误提示
            return Result.error("type参数不能为空，且只能为expense或income");
        }
        return Result.success(pageResult);
    }

    //删除流水
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id, @RequestParam String type) {
        log.info("删除流水:{},{}", id,type);
        transactionsService.delete(id,type);
        return Result.success("删除成功");
    }

    //修改流水
    @PutMapping("/{id}")
    public Result update(@PathVariable Integer id, @RequestBody TransactionsDTO transactionsDTO) {
        log.info("修改流水:{},{}", id, transactionsDTO);
        transactionsService.update(id, transactionsDTO);
        return Result.success("修改成功");
    }

}
